package com.yiya.ms.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.yiya.bean.Employee;
import com.yiya.bean.SysRole;
import com.yiya.bean.SysUser;
import com.yiya.bean.BaseBean.STATE;
import com.yiya.exception.ServiceException;
import com.yiya.model.EmployeeModel;
import com.yiya.model.EmployeeReceiveModel;
import com.yiya.model.SerCompanyCplex;
import com.yiya.model.SerCompanyCplexModel;
import com.yiya.model.SysUserModel;
import com.yiya.ms.annotation.Auth;
import com.yiya.service.EmployeeService;
import com.yiya.service.MailService;
import com.yiya.service.SerCompanyService;
import com.yiya.service.SysRoleService;
import com.yiya.service.SysUserService;
import com.yiya.utils.HtmlUtil;
import com.yiya.utils.MethodUtil;
import com.yiya.utils.SessionUtils;

@Controller
@RequestMapping("/employee")
public class EmployeeAction extends BaseAction {
	@SuppressWarnings("unused")
	private final static Logger log = Logger.getLogger(EmployeeAction.class);

	@Autowired
	private SysUserService<SysUser> sysUserService;

	@Autowired(required = false)
	private SysRoleService<SysRole> sysRoleService;

	@Autowired
	private EmployeeService employeeService;
	
	@Autowired
	private SerCompanyService serCompanyService;
	
	@Autowired
	private MailService mailService;

	@RequestMapping("/list")
	public ModelAndView list(SysUserModel model, HttpServletRequest request)
			throws Exception {
		Map<String, Object> context = getRootMap();
		return forword("employee/employee", context);
	}

	@RequestMapping("/dataList")
	public void dataList(SysUserModel model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		SysUser u = SessionUtils.getUser(request);
		if (u.getSuperAdmin() != 1) {
			Employee employee = employeeService.queryByUserId(u.getId());
			model.setCompanyId(employee.getSerCompanyId());
		}

		if (model.getUserType() == null || !(1 == model.getUserType())) {
			model.setUserType(1);
		}
		List<SysUser> dataList = sysUserService.queryByList(model);
		for (SysUser user : dataList) {
			List<SysRole> list = sysRoleService.queryByUserid(user.getId());
			user.setRoleStr(rolesToStr(list));
		}
		// 设置页面数据
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("total", model.getPager().getRowCount());
		jsonMap.put("rows", dataList);
		HtmlUtil.writerJson(response, jsonMap);
	}

	@RequestMapping("/save")
	public void save(EmployeeReceiveModel bean, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (bean != null) {
			SysUser user = SessionUtils.getUser(request);
			Date nowTime = new Date();
			SysUser sysUser = new SysUser();
			sysUser.setId(bean.getSysUserId());
			sysUser.setEmail(bean.getEmail());
			sysUser.setNickName(bean.getNickName());
			sysUser.setState(bean.getState());
			sysUser.setUserType(bean.getUserType());
			sysUser.setCompanyId(bean.getSerCompanyId());
			sysUser.setDeleted(0);
			Employee employee = new Employee();
			employee.setId(bean.getEmployeeId());
			employee.setName(bean.getName());
			employee.setMobileNumber(bean.getMobileNumber());
			employee.setSerCompanyId(bean.getSerCompanyId());
			employee.setUserId(sysUser.getId());
			int count = sysUserService.getUserCountByEmail(sysUser.getEmail());
			if (sysUser.getId() == null) {
				if (count > 0) {
					throw new ServiceException("用户已存在.");
				}
				sysUser.setCreateBy(user.getId());
				sysUserService.addSysUser(sysUser);
				employee.setUserId(sysUser.getId());
				employee.setCreateBy(user.getId());
				employee.setCreateTime(nowTime);
				employeeService.add(employee);
			} else {
				if (count > 1) {
					throw new ServiceException("用户已存在.");
				}
				sysUser.setUpdateBy(user.getId());
				sysUserService.updateBySelective(sysUser);
				int employeeCount = employeeService
						.getEmployeeCountByUserId(sysUser.getId());
				if (employeeCount == 0) {
					employee.setUserId(sysUser.getId());
					employee.setCreateBy(user.getId());
					employee.setCreateTime(nowTime);
					employeeService.add(employee);
				} else {
					employee.setUpdateBy(user.getId());
					employee.setUpdateTime(nowTime);
					employeeService.updaeBySelective(employee);
				}
			}
			sendSuccessMessage(response, "保存成功");
		} else {
			sendFailureMessage(response, "保存失败");
		}
	}

	/**
	 * 角色列表转成字符串
	 * 
	 * @param list
	 * @return
	 */
	private String rolesToStr(List<SysRole> list) {
		if (list == null || list.isEmpty()) {
			return null;
		}
		StringBuffer str = new StringBuffer();
		for (int i = 0; i < list.size(); i++) {
			SysRole role = list.get(i);
			str.append(role.getRoleName());
			if ((i + 1) < list.size()) {
				str.append(",");
			}
		}
		return str.toString();
	}

	@RequestMapping("/getId")
	public void getId(Integer id, HttpServletResponse response)
			throws Exception {
		Map<String, Object> context = getRootMap();
		SysUser sysUser = sysUserService.queryById(id);
		Employee employee = employeeService.queryByUserId(id);
		if (sysUser == null) {
			sendFailureMessage(response, "没有找到对应的记录!");
			return;
		}
		EmployeeModel bean = new EmployeeModel();
		bean.setSysUser(sysUser);
		bean.setEmployee(employee);
		context.put(SUCCESS, true);
		context.put("data", bean);
		HtmlUtil.writerJson(response, context);
	}

	@RequestMapping("/delete")
	public void delete(Integer[] id, HttpServletResponse response)
			throws Exception {
		sysUserService.delete(id);
		sendSuccessMessage(response, "删除成功");
	}

	@RequestMapping("/loadEmployeeList")
	public void loadCompanyList(EmployeeReceiveModel model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		SysUser user = SessionUtils.getUser(request);
		List<Employee> list = new ArrayList<Employee>();
		if(user.getSuperAdmin()!=1){
			String serCompanyId = request.getParameter("serCompanyId");
			if (serCompanyId != null && !"".equals(serCompanyId)) {
				System.out.println(serCompanyId);
				model.setSerCompanyId(Integer.valueOf(serCompanyId));
				list = employeeService.selectAllBySerCompanyId(model);
			}
		}else{
			list = employeeService.selectAllBySerCompanyId(model);
		}
		
		HtmlUtil.writerJson(response, list);
	}
	
	@Auth(verifyLogin=false,verifyURL=false)
	@RequestMapping("/toRegist")
	public void toRegist(EmployeeReceiveModel bean,HttpServletRequest request,HttpServletResponse response) throws Exception{
		Map<String,Object> context = getRootMap();
		SerCompanyCplexModel param = new SerCompanyCplexModel();
		List<SerCompanyCplex> companies = serCompanyService.getSerCompanyList(param);
		context.put("companies", companies);
		
		String vcode  = SessionUtils.getValidateCode(request);
		SessionUtils.removeValidateCode(request);//清除验证码，确保验证码只能用一次
		
		if(bean!=null){
			if(StringUtils.isBlank(bean.getVerifyCode())){
				sendFailureMessage(response, "验证码不能为空.");
				return;
			}
			//判断验证码是否正确
			if(!bean.getVerifyCode().toLowerCase().equals(vcode)){
				sendFailureMessage(response, "验证码输入错误.");
				return;
			}
			SysUser user = SessionUtils.getUser(request);
			Date nowTime = new Date();
			SysUser sysUser = new SysUser();
			sysUser.setId(bean.getSysUserId());
			sysUser.setEmail(bean.getEmail());
			sysUser.setNickName(bean.getNickName());
			sysUser.setPwd(MethodUtil.MD5(bean.getPwd()));
			sysUser.setState(2);
			sysUser.setUserType(1);
			sysUser.setCompanyId(bean.getSerCompanyId());
			sysUser.setDeleted(0);
			Employee employee = new Employee();
			employee.setId(bean.getEmployeeId());
			employee.setName(bean.getName());
			employee.setMobileNumber(bean.getMobileNumber());
			employee.setSerCompanyId(bean.getSerCompanyId());
			employee.setUserId(sysUser.getId());
			int count = sysUserService.getUserCountByEmail(sysUser.getEmail());
			if (sysUser.getId() == null) {
				if (count > 0) {
					sendFailureMessage(response, "用户已存在.");
					return;
				}
				sysUserService.addSysUser(sysUser);
				employee.setUserId(sysUser.getId());
				employee.setCreateTime(nowTime);
				employeeService.add(employee);
			} else {
				if (count > 1) {
					sendFailureMessage(response, "用户已存在.");
					return;
				}
				sysUser.setUpdateBy(user.getId());
				sysUserService.updateBySelective(sysUser);
				int employeeCount = employeeService.getEmployeeCountByUserId(sysUser.getId());
				if (employeeCount == 0) {
					employee.setUserId(sysUser.getId());
					employee.setCreateBy(user.getId());
					employee.setCreateTime(nowTime);
					employeeService.add(employee);
				} else {
					employee.setUpdateBy(user.getId());
					employee.setUpdateTime(nowTime);
					employeeService.updaeBySelective(employee);
				}
			}
			mailService.sendValidateMail(sysUser.getId());
			sendSuccessMessage(response, "注册成功，请到邮箱及时完成校验");
		}else{
			sendFailureMessage(response, "注册失败");
		}
	}
	
	/**
	 * 用户授权页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/userRole") 
	public ModelAndView  userRole(HttpServletRequest request) throws Exception{
		Map<String,Object>  context = getRootMap();
		return forword("/employee/sysUserRole", context);
	}
	
	/**
	 * 用户授权列表
	 * @param model
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/userList") 
	public void  userList(SysUserModel model,HttpServletRequest request,HttpServletResponse response) throws Exception{
		model.setState(STATE.ENABLE.key);
		dataList(model,request,response);
	}
	
	@RequestMapping("/loadRoleList")
	public void loadRoleList(HttpServletResponse response) throws Exception{
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("roleType", 1);
		List<SysRole>  roloList = sysRoleService.queryAllList(param);
		HtmlUtil.writerJson(response, roloList);
	}
}
